import { defineStore } from 'pinia'
import { ref } from 'vue'

interface CommonItem {
    id: number
    name: string
    value: string
    createdAt: Date
}

export const commonStore = defineStore('common', () => {
    const items = ref<CommonItem[]>([])

    // 从localStorage加载数据
    const loadFromLocalStorage = () => {
        try {
            const stored = localStorage.getItem('commonStore')
            if (stored) {
                const parsedItems = JSON.parse(stored)
                items.value = parsedItems.map((item: any) => ({
                    ...item,
                    createdAt: new Date(item.createdAt)
                }))
            }
        } catch (error) {
            console.error('Failed to load from localStorage:', error)
        }
    }

    // 保存到localStorage
    const saveToLocalStorage = () => {
        try {
            localStorage.setItem('commonStore', JSON.stringify(items.value))
        } catch (error) {
            console.error('Failed to save to localStorage:', error)
        }
    }

    //根据id添加数据
    const addItem = (item: CommonItem) => {
        // 检查是否已存在相同ID的项目
        const existingIndex = items.value.findIndex(existingItem => existingItem.id === item.id)
        if (existingIndex !== -1) {
            // 如果存在，更新现有项目
            items.value[existingIndex] = item
        } else {
            // 如果不存在，添加新项目
            items.value.push(item)
        }
        // 保存到localStorage
        saveToLocalStorage()
    }

    // 根据ID获取
    const getItemById = (id: number | string) => {
        return items.value.find(item => item.id === id)
    }

    // 更新
    const updateItem = (id: number, updates: Partial<CommonItem>) => {
        const index = items.value.findIndex(item => item.id === id)
        if (index !== -1) {
            items.value[index] = { ...items.value[index], ...updates }
            saveToLocalStorage()
            return items.value[index]
        }
        return null
    }

    // 删除
    const removeItem = (id: number) => {
        const index = items.value.findIndex(item => item.id === id)
        if (index !== -1) {
            const [removedItem] = items.value.splice(index, 1)
            saveToLocalStorage()
            return removedItem
        }
        return null
    }

    // 获取所有
    const getAllItems = () => {
        return items.value
    }

    // 清空所有
    const clearItems = () => {
        items.value = []
    }

    // 初始化时加载数据
    loadFromLocalStorage()

    return {
        items,
        addItem,
        getItemById,
        updateItem,
        removeItem,
        getAllItems,
        clearItems,
        loadFromLocalStorage,
        saveToLocalStorage
    }
})
